﻿using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ColiyerWpfControl.Gis.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    internal class ControlViewModel
    {
        public ControlViewModel()
        {
            Type type = this.GetType();
            IEnumerable<PropertyInfo> pps = type.GetProperties().Where(x => x.CanWrite && x.CanRead);

            foreach (PropertyInfo item in pps)
            {
                var attr = item.GetCustomAttribute<NormalCmdAttribute>();
                if (attr != null)
                {
                    if (string.IsNullOrEmpty(attr.CallMethodName))
                        throw new ArgumentNullException(nameof(attr.CallMethodName), "RelayCmdInjectAttribute 缺少指定的方法名称。");

                    MethodInfo method = type.GetMethod(attr.CallMethodName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
                    if (method == null)
                        throw new ArgumentException($"指定的方法 '{attr.CallMethodName}' 在类型 '{type.Name}' 中不存在。");


                    // 检查方法是否为无参的 void 方法
                    if (method.ReturnType != typeof(void) || method.GetParameters().Length != 0)
                    {
                        throw new InvalidOperationException($"方法 '{attr.CallMethodName}' 的签名必须为 'void MethodName()'。");
                    }


                    // 使用 Delegate.CreateDelegate 创建委托
                    Action actionDelegate = (Action)Delegate.CreateDelegate(typeof(Action), this, method);
                    NormalCommand cmd = new NormalCommand(actionDelegate);

                    item.SetValue(this, cmd);
                }
            }

        }
    }
}
